#include "socket.hpp"
#include <thread>


class TcpServer{
    
    using func_t = std::function<void(std::shared_ptr<Net_TcpSocket:: Socket>)> ; 
    public:
    TcpServer(uint16_t port,func_t task)
    :_port(port)
    ,_listensocket(new Net_TcpSocket::TcpSocket,[](Net_TcpSocket::TcpSocket* &ptr){delete ptr; ptr = nullptr;})
    ,_hander_request(task)
    {
        _listensocket->BuildListenSocket(port,Net_TcpSocket::default_backlog);
    }
    ~TcpServer()
    {

    }
    void WorkLoop()
    {
        while(1)
        {                
            std::string peerip;   
            uint16_t peerport;
            std::shared_ptr<Net_TcpSocket:: Socket> newsock ( _listensocket->AcceptConnection(&peerip,&peerport));
            if(!newsock) continue;
            std::cout<<"获取了新连接:Client Ip"<<peerip<<", peer Port"<<peerport<<"\n";
            
            std::thread td(_hander_request,newsock);
            td.detach();
        }
    }
    private:
    int _port;
    std::shared_ptr<Net_TcpSocket::Socket> _listensocket;
    func_t _hander_request;
};